"""
Trading Service 依赖注入
=====================

为Trading Service提供统一的依赖管理和数据库连接
"""


# 使用RedFire框架
import logging
import sys
import os
from typing import Generator, AsyncGenerator, Optional
from fastapi import Depends, HTTPException, status, Request
from sqlalchemy.orm import Session
from sqlalchemy.ext.asyncio import AsyncSession

# 使用RedFire框架的依赖注入系统
from backend.redfire_framework.core.container import RedFireContainer
from backend.redfire_framework.core.database import DatabaseManager
from backend.redfire_framework.cache.backends import RedisCache
from backend.redfire_framework.data_processing.engine import RealtimeDataEngine

logger = logging.getLogger(__name__)

# 创建交易服务容器
_trading_container = None

def get_trading_container() -> RedFireContainer:
    """获取交易服务容器"""
    global _trading_container
    if _trading_container is None:
        from backend.redfire_framework.core.config import get_service_settings
        config = get_service_settings("trading-service")
        _trading_container = RedFireContainer.create_for_service("trading-service", config)
    return _trading_container

# 数据库会话依赖
async def get_db() -> AsyncGenerator[AsyncSession, None]:
    """获取数据库会话（使用RedFire框架）"""
    try:
        container = get_trading_container()
        db_manager = container.database_manager()
        async with db_manager.get_session() as session:
            yield session
    except Exception as e:
        logger.error(f"获取数据库会话失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="数据库连接失败"
        )

async def get_async_db() -> AsyncGenerator[AsyncSession, None]:
    """获取异步数据库会话"""
    # 复用get_db函数
    async for db in get_db():
        yield db

# 读写分离会话依赖
async def get_read_db() -> AsyncGenerator[AsyncSession, None]:
    """获取只读数据库会话"""
    try:
        container = get_trading_container()
        db_manager = container.database_manager()
        async with db_manager.get_read_session() as session:
            yield session
    except Exception as e:
        logger.error(f"获取只读数据库会话失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="数据库连接失败"
        )

async def get_write_db() -> AsyncGenerator[AsyncSession, None]:
    """获取写入数据库会话"""
    try:
        container = get_trading_container()
        db_manager = container.database_manager()
        async with db_manager.get_write_session() as session:
            yield session
    except Exception as e:
        logger.error(f"获取写入数据库会话失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="数据库连接失败"
        )

# Redis缓存依赖
async def get_redis():
    """获取Redis客户端（使用RedFire框架）"""
    try:
        container = get_trading_container()
        cache_backend = container.cache_backend()
        return cache_backend.client
    except Exception as e:
        logger.error(f"获取Redis客户端失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="缓存服务不可用"
        )

# 交易服务专用依赖
class TradingDependencies:
    """交易服务依赖集合"""
    
    def __init__(self):
        # 注意：缓存管理器现在是异步的，需要在使用时再获取
        self.influx_manager = get_influx_manager()
        self.rw_manager = get_rw_split_manager()
    
    def get_order_cache_key(self, user_id: int, order_id: str) -> str:
        """生成订单缓存键"""
        return f"trading:order:{user_id}:{order_id}"
    
    def get_position_cache_key(self, user_id: int, symbol: str) -> str:
        """生成持仓缓存键"""
        return f"trading:position:{user_id}:{symbol}"
    
    def get_balance_cache_key(self, user_id: int, currency: str = "CNY") -> str:
        """生成余额缓存键"""
        return f"trading:balance:{user_id}:{currency}"
    
    def get_price_cache_key(self, symbol: str) -> str:
        """生成价格缓存键"""
        return f"trading:price:{symbol}"

# 全局交易依赖实例
_trading_deps = None

def get_trading_deps() -> TradingDependencies:
    """获取交易依赖"""
    global _trading_deps
    if _trading_deps is None:
        _trading_deps = TradingDependencies()
    return _trading_deps

# 交易引擎依赖
def get_trading_engine():
    """获取交易引擎实例"""
    from ..core.trading_engine import TradingEngine
    
    deps = get_trading_deps()
    return TradingEngine(
        db_manager=deps.db_manager,
        cache_manager=deps.cache_manager,
        influx_manager=deps.influx_manager
    )

# 风险管理器依赖
def get_risk_manager():
    """获取风险管理器实例"""
    from ..core.risk_manager import RiskManager
    
    deps = get_trading_deps()
    return RiskManager(
        db_manager=deps.db_manager,
        cache_manager=deps.cache_manager
    )

# 持仓计算器依赖
def get_position_calculator():
    """获取持仓计算器实例"""
    from ..core.position_calculator import PositionCalculator
    
    deps = get_trading_deps()
    return PositionCalculator(
        db_manager=deps.db_manager,
        cache_manager=deps.cache_manager
    )

# 交易服务依赖
def get_trading_service():
    """获取交易服务实例"""
    from ..services.trading_service import TradingService
    
    deps = get_trading_deps()
    return TradingService(
        db_manager=deps.db_manager,
        cache_manager=deps.cache_manager
    )

# 健康检查依赖
async def check_trading_service_health() -> dict:
    """检查交易服务健康状态"""
    health_status = {
        "service": "trading-service",
        "status": "healthy",
        "checks": {}
    }
    
    try:
        # 检查数据库连接
        db_manager = get_db_manager()
        db_stats = db_manager.get_all_stats()
        health_status["checks"]["database"] = {
            "status": "healthy" if db_stats else "unhealthy",
            "stats": db_stats
        }
    except Exception as e:
        health_status["checks"]["database"] = {
            "status": "unhealthy",
            "error": str(e)
        }
    
    try:
        # 检查Redis缓存
        redis_client = get_redis()
        redis_client.ping()
        health_status["checks"]["redis"] = {"status": "healthy"}
    except Exception as e:
        health_status["checks"]["redis"] = {
            "status": "unhealthy", 
            "error": str(e)
        }
    
    try:
        # 检查InfluxDB
        influx_manager = get_influx_manager()
        if influx_manager.test_connection():
            health_status["checks"]["influxdb"] = {"status": "healthy"}
        else:
            health_status["checks"]["influxdb"] = {"status": "unhealthy"}
    except Exception as e:
        health_status["checks"]["influxdb"] = {
            "status": "unhealthy",
            "error": str(e)
        }
    
    # 检查整体状态
    unhealthy_checks = [
        check for check in health_status["checks"].values() 
        if check["status"] == "unhealthy"
    ]
    
    if unhealthy_checks:
        health_status["status"] = "degraded" if len(unhealthy_checks) < len(health_status["checks"]) else "unhealthy"
    
    return health_status

# 使用统一认证系统
# from backend.redfire_framework.core.dependencies import get_current_user, require_permissions
# 注意：这些函数在重构中被移除，需要使用新的安全服务

# 交易服务专用权限验证
def require_trading_permission(permission: str):
    """要求交易相关权限"""
    # 使用新的安全服务实现权限验证
    def permission_checker():
        # 这里应该使用 SecurityService 来验证权限
        pass
    return permission_checker

def require_trading_admin():
    """要求交易管理员权限"""
    # 使用新的安全服务实现管理员权限验证
    def admin_checker():
        # 这里应该使用 SecurityService 来验证管理员权限
        pass
    return admin_checker

# 清理资源（统一系统自动管理）
def cleanup_trading_dependencies():
    """清理交易服务依赖资源"""
    try:
        # 统一依赖注入系统会自动管理资源清理
        # 使用容器的清理方法
        global _trading_container
        if _trading_container:
            # 容器会自动管理资源清理
            pass
        logger.info("交易服务依赖资源清理完成")
    except Exception as e:
        logger.error(f"清理交易服务依赖资源失败: {e}")